﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

public partial class Administrator_poll : System.Web.UI.UserControl
{
   
            #region Public Properties
    public int PollID
    {
        get 
        {
            if (ViewState["PollID"] == null)
                return -1;
            else
                return (int)ViewState["PollID"];
        }
        set { ViewState["PollID"] = value; }
    }

    public bool PollEnabled
    {
        get
        {
            if (ViewState["PollEnabled"] == null)
                return true;
            else
                return (bool)ViewState["PollEnabled"];
        }
        set { ViewState["PollEnabled"] = value; }
    }
    #endregion

    #region SqlDataSource Control Event Handlers
    /*
     * The following three event handlers are used to populate the @PollID parameter
     * based on the User Control's PollID property for assorted SqlDataSource controls...
     */
    protected void PollDataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
        e.Command.Parameters["@PollID"].Value = PollID;
    }
    protected void PollAnswersDataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
        e.Command.Parameters["@PollID"].Value = PollID;
    }
    protected void PollResultsDataSource_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
    {
        e.Command.Parameters["@PollID"].Value = PollID;
    }

    // Sets the @UserID parameter when voting in order to associate the currently logged on
    // user's UserId value with the vote.
    protected void PollAnswersDataSource_Inserting(object sender, SqlDataSourceCommandEventArgs e)
    {
        //Guid userID = Guid.Empty;
        //MembershipUser currentUser = Membership.GetUser();
        //if (currentUser != null)
        //    userID = (Guid)currentUser.ProviderUserKey;

        //e.Command.Parameters["@Users_ID"].Value = userID;
    }
    #endregion

    #region PollFormView DataBound Event Handler
    // This event handler fires when data is bound to the FormView. It shows either
    // the poll taking or poll results interface depending on the result of
    // CanUserTakePoll() method. If PollEnabled is false, then the poll results are
    // always shown, regardless of what CanUserTakePoll() returns.
    // EXTENSION POINT: If you want to modify what users can take the poll (such as allowing
    //                  anonymous users), modify the CanUserTakePoll() method...)
    protected void PollFormView_DataBound(object sender, EventArgs e)
    {
        // Determine if the user can take the poll
        bool showResults;
        if (!PollEnabled)
            showResults = true;
        else
            showResults = !CanUserTakePoll();

        // Show/hide the Panels based on the value of showResults
        Panel takePollPanel = PollFormView.FindControl("pnlTakePoll") as Panel;
        if (takePollPanel != null)
            takePollPanel.Visible = !showResults;

        Panel pollResultsPanel = PollFormView.FindControl("pnlPollResults") as Panel;
        if (pollResultsPanel != null)
            pollResultsPanel.Visible = showResults;
    }
    #endregion

    #region "Vote" Button Click Event Handler
    // When the "Vote" button is clicked, this event handler executes. It calls the
    // PollAnswersDataSource's Insert() method, thereby INSERTing a record into the
    // UserResponses table. It then rebinds the data to the control, which causes the
    // poll interface to be updated, showing the poll results (since the user has now
    // taken the poll) and with the updated poll results.
    protected void btnSubmitVote_Click(object sender, EventArgs e)
    {
        SqlDataSource answersDataSource = PollFormView.FindControl("PollAnswersDataSource") as SqlDataSource;
        answersDataSource.Insert();

        PollFormView.DataBind();        // rebind the data to the poll interface
    }
    #endregion

    #region ResultsDataList Event Handlers
    // Determines how many total votes have been cast for this poll. Used to determine the
    // percentages for each answer as well as for displaying the total number of votes in
    // the TotalVotesLabel Label. 
    private int totalVotes = 0;
    protected void resultsDataList_DataBinding(object sender, EventArgs e)
    {
        // Calculate the total # of votes
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["up1vnConnectionString"].ConnectionString))
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM UserResponses r INNER JOIN PollAnswers a ON r.PollAnswerID = a.PollAnswerID WHERE a.PollID = @PollID", conn);
            cmd.Parameters.Add(new SqlParameter("@PollID", PollID));
            totalVotes = (int)cmd.ExecuteScalar();
            conn.Close();
        }

        // Display the # of votes
        Label TotalVotesLabel = PollFormView.FindControl("TotalVotesLabel") as Label;
        TotalVotesLabel.Text = string.Format("{0:d} votes...", totalVotes);
    }


    // This event handler fires once for each poll answer when viewing the results.
    // It determines the number of votes for each answer and computes and displays the percentage.
    protected void resultsDataList_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        // Determine how many votes were made for this answer...
        int votes = (int)DataBinder.Eval(e.Item.DataItem, "Votes");

        // Programmatically access the Label & Image controls...
        Label percentLabel = (Label)e.Item.FindControl("PercentageLabel");
        Image percentImage = (Image)e.Item.FindControl("PercentageImage");
        
        // Calculate the percentage...
        if (totalVotes > 0)
        {
            double pct = (Convert.ToDouble(votes) / Convert.ToDouble(totalVotes)) * Convert.ToDouble(100);
            percentLabel.Text = pct.ToString("0.0") + "%";
            percentImage.Width = Unit.Percentage(pct);
        }
        else
        {
            percentLabel.Text = "0%";
            percentImage.Visible = false;
        }
    }
    #endregion

    #region CanUserTakePoll Method (EXTENSION POINT)
    // Determines whether a user can take the poll or if the results must be shown.
    // My implementation only allows authenticated users who have not already taken the
    // poll to vote. 
    // EXTENSION POINT: If you want to modify what users can take the poll (such as allowing
    //                  anonymous users), modify the CanUserTakePoll() method...)
    private bool CanUserTakePoll()
    {
        // Anonymous visitors cannot take poll
        if (!Request.IsAuthenticated)
            return false;

        // Determine if this user has already taken this poll... if so, she cannot retake it.
        MembershipUser currentUser = Membership.GetUser();
        if (currentUser != null)
        {
            Guid userID = (Guid)currentUser.ProviderUserKey;
            bool hasUserTakenPoll = false;

            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["up1vnConnectionString"].ConnectionString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM UserResponses r INNER JOIN PollAnswers a ON r.PollAnswerID = a.PollAnswerID WHERE a.PollID = @PollID AND r.UserID = @UserID", conn);
                cmd.Parameters.Add(new SqlParameter("@PollID", PollID));
                cmd.Parameters.Add(new SqlParameter("@UserID", userID));

                hasUserTakenPoll = ((int)cmd.ExecuteScalar()) > 0;
                conn.Close();
            }

            return hasUserTakenPoll == false;
        }

        return false;
    }
    #endregion
    }
